/**
 * get day of week, from monday(0) to sunday(6)
 * @param date {Date || undefined} - optional, default is new Date()
 * @returns {number}
 */
export const getDayOfWeek = (date = new Date()) => {
    const dayOfWeek = date.getDay();
    return dayOfWeek === 0 ? 6 : dayOfWeek - 1;
}

export const WEEK = [
    {index: 0, name: "星期一"},
    {index: 1, name: "星期二"},
    {index: 2, name: "星期三"},
    {index: 3, name: "星期四"},
    {index: 4, name: "星期五"},
    {index: 5, name: "星期六"},
    {index: 6, name: "星期日"}
];

export const WORKDAYS = [true, true, true, true, true, false, false];

export const thisMonday = () => {
    const today = new Date();
    const dayOfWeek = getDayOfWeek(today);
    const monday = dayOfWeek === 0 ? today : new Date(today.setDate(today.getDate() - dayOfWeek));
    monday.setHours(0, 0, 0, 0);
    return monday;
}

// convert config to proper date times
export const toTimes = (monday, dayOfWeek, halfHour, configString) => {

    const result = [];

    for (let i = 0; i < 24; i++) {
        if (configString.charAt(i) === '1') {
            const v = new Date(monday);
            if (dayOfWeek.index > 0) {
                v.setDate(dayOfWeek.index);
            }
            v.setHours(i);
            result.push(v);

            if (halfHour) {
                const v2 = new Date(v);
                v2.setMinutes(30);
                result.push(v2);
            }
        }
    }

    return result;
}

export const YYYYMMDD = "YYYY-MM-DD";

/**
 * format date to string with format "YYYY-MM-DD"
 * @param date - a dayjs date object
 * @returns {string}
 */
export const formatDate = date => {
    return date?.format(YYYYMMDD) || "";
}

/**
 * format date to string with format "HH:mm"
 * @param date {Date}
 * @returns {`${string}:${string}`}
 */
export const formatHm = date => {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `${hours}:${minutes}`;
}

/**
 * check if date is today
 * @param date {Date}
 * @returns {boolean}
 */
export const today = date => {
    const today = new Date();
    return date.getFullYear() === today.getFullYear() &&
        date.getMonth() === today.getMonth() &&
        date.getDate() === today.getDate();
}
